package com.cskaoyan.service;

import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.domain.Permission;
import com.cskaoyan.bean.domain.PermissionExample;
import com.cskaoyan.bean.domain.Role;
import com.cskaoyan.bean.domain.RoleExample;
import com.cskaoyan.bean.roleBeans.PermissionResultVo;
import com.cskaoyan.bean.roleBeans.PermissionVo;
import com.cskaoyan.bean.roleBeans.RolePartInfoBean;
import com.cskaoyan.exception.MySQLDuplicateEntryException;
import com.cskaoyan.mapper.AuthMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @User: Yr
 * @Date: 2021/12/1 10:41
 * @Description: 系统管理-角色管理模块 service实现类
 */

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    AuthMapper authMapper;


    /**
     * 按条件查询roleList
     * (仅显示deleted为false的)
     */
    @Override
    public BaseData list(String name, BaseParam baseParam) {

        //开启分页
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        //查询数据
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria().andDeletedEqualTo(false);
        if (name != null) criteria.andNameLike("%" + name + "%");
        roleExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        List<Role> roleList = roleMapper.selectByExample(roleExample);
        //返回数据及分页信息
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        BaseData data = BaseData.getBack(baseParam.getLimit(), pageInfo.getPageNum(),
                pageInfo.getPages(), (int) pageInfo.getTotal(), roleList);
        return data;
    }


    /**
     * 逻辑删除
     * (deleted设置为true)
     */
    @Override
    public int delete(Role role) {
        Role example = new Role();
        example.setId(role.getId());
        example.setDeleted(true);
        int affectedRows = roleMapper.updateByPrimaryKeySelective(example);
        return affectedRows;
    }

    /**
     * 新增role
     */
    @SneakyThrows
    @Override
    public Role create(Role role) {

        //新增前先查询deleted为false的 是否重名
        RoleExample example = new RoleExample();
        example.createCriteria().andDeletedEqualTo(false).andNameEqualTo(role.getName());
        List<Role> roleList = roleMapper.selectByExample(example);
        if (roleList.size() > 0) return null;
        //执行插入 若抛出异常 表示deleted为true的角色有重名
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        try {
            roleMapper.insertSelective(role);
        } catch (Exception e) {
            throw new MySQLDuplicateEntryException();
        }
        return role;
    }

    /**
     * 更新role
     */
    @Override
    public int update(Role role) {
        role.setUpdateTime(new Date());
        int affectedRows;
        try {
            affectedRows = roleMapper.updateByPrimaryKeySelective(role);
        } catch (Exception e) {
            affectedRows = 0;
        }
        return affectedRows;
    }

    /**
     * option 获取所有role的id和name数据
     */
    @Override
    public BaseData options() {

        //统计deleted为false的所有role数量
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andDeletedEqualTo(false);
        Integer count = Math.toIntExact(roleMapper.countByExample(roleExample));
        //获取deleted为false的role数据
        List<RolePartInfoBean> rolePartInfoBeanList = new ArrayList<>();
        List<Role> roleList = roleMapper.selectByExample(roleExample);
        for (Role role : roleList) {
            RolePartInfoBean rolePartInfoBean = new RolePartInfoBean();
            rolePartInfoBean.setLabel(role.getName());
            rolePartInfoBean.setValue(role.getId());
            rolePartInfoBeanList.add(rolePartInfoBean);
        }
        BaseData data = BaseData.getBack(count, 1, 1, count, rolePartInfoBeanList);
        return data;
    }

    /**
     * 获取权限信息插入数据库
     */
    @Override
    public void getAuthData(List<PermissionVo> list) {

//        for (PermissionVo permissionVo : list) {
//            //遍历插入 一级权限
//            int countL1 = roleMapper.insertToAuth(0, permissionVo.getId(), permissionVo.getLabel(), 1, null);
//        }

//        //插入 二级权限
//        for (PermissionVo permissionVo : list) {
//            //---先拿到对应的一级权限的id作为自己的pid
//            int pid = roleMapper.getPid(permissionVo.getId(), 1);
//            List<PermissionVo.ChildrenData> childrenList = permissionVo.getChildren();
//            for (PermissionVo.ChildrenData child : childrenList) {
//                roleMapper.insertToAuth(pid, child.getId(), child.getLabel(), 2, null);
//            }
//        }

        //插入 三级权限
        for (PermissionVo permissionVo : list) {
            List<PermissionVo.ChildrenData> childList = permissionVo.getChildren();
            for (PermissionVo.ChildrenData child : childList) {
                //---先拿到对应的二级权限的id作为自己的pid
                int pid = roleMapper.getPid(child.getId(), 2);
                List<PermissionVo.ChildrenData.GrandChildrenData> grandChildrenList = child.getChildren();
                for (PermissionVo.ChildrenData.GrandChildrenData grandChild : grandChildrenList) {
                    roleMapper.insertToAuth(pid, grandChild.getId(), grandChild.getLabel(), 3, grandChild.getApi());
                }
            }
        }

    }

    /**
     * 根据roleId返回对应权限数据
     */
    @Override
    public PermissionResultVo permissionsByGet(Integer roleId) {
        //获取assignedPermissions数据
        List<String> assignedPermissions;
        if (roleId == 1) {
            //超级管理员则返回auth表内全部权限
            assignedPermissions = authMapper.selectPermissionsByLevel(3);
        } else {
            //其他管理员正常返回permission表权限
            PermissionExample example = new PermissionExample();
            example.createCriteria().andRoleIdEqualTo(roleId);
            List<Permission> permissions = permissionMapper.selectByExample(example);
            assignedPermissions = new ArrayList<>();
            for (Permission permission : permissions) {
                assignedPermissions.add(permission.getPermission());
            }
        }
        //获取systemPermissions数据
        //--封装第一层
        List<PermissionVo> systemPermissions = authMapper.selectByLevel(1);
        //--封装第二层 根据pid
        for (PermissionVo sp : systemPermissions) {
            List<PermissionVo.ChildrenData> childList = authMapper.selectChildByPid(sp.getNum());
            sp.setChildren(childList);
            sp.setNum(null);
            //--封装第三层 根据pid
            for (PermissionVo.ChildrenData child : childList) {
                List<PermissionVo.ChildrenData.GrandChildrenData> grandChildList = authMapper.selectGrandChildByPid(child.getNum());
                child.setChildren(grandChildList);
                child.setNum(null);
            }
        }
        //返回全部数据
        PermissionResultVo permissionResultVo = new PermissionResultVo();
        permissionResultVo.setAssignedPermissions(assignedPermissions);
        permissionResultVo.setSystemPermissions(systemPermissions);
        return permissionResultVo;
    }

    /**
     * 给指定roleId分配新权限
     */
    @Override
    public int permissionsByPost(Integer roleId, ArrayList<String> permissions) {
        //先删除旧权限
        PermissionExample example = new PermissionExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        permissionMapper.deleteByExample(example);
        //分配新权限
        int i = 0;
        for (String permissionStr : permissions) {
            Permission permission = new Permission();
            permission.setRoleId(roleId);
            permission.setPermission(permissionStr);
            permission.setAddTime(new Date());
            permission.setUpdateTime(new Date());
            int affectedRows = permissionMapper.insertSelective(permission);
            if (affectedRows == 1) i++;
        }
        return i;
    }


}
